import { storage } from 'wxt/storage'
import { type WindwoMessageEventMap, type WokrsUserIds } from 'shared/types/index'
import { worksIdStorageKey } from 'shared/utils/index'
import { useWindowMessage } from 'shared/message/window'

const { onMessage } = useWindowMessage<WindwoMessageEventMap>('content')

export default defineContentScript({
  matches: ['*://*.chrome.com/*', '*://*.douyin.com/*'],
  main() {
    onMessage('works', async (data) => {
      const keys = await storage.getItem<WokrsUserIds>(worksIdStorageKey, { fallback: [] })
      if (!keys.includes(data.uid)) {
        keys.push(data.uid)
        storage.setItem(worksIdStorageKey, keys)
      }
      
      const key = `local:${data.uid}` as const
      const source = await storage.getItem(key, { fallback: {} })
      storage.setItem(key, Object.assign(source, data))
    })
  },
})
